<template>
  <label>
    <span>
      <input v-if="group" type="checkbox" :disabled="disabled" :value="label" v-model="model" @change="change">
      <input v-else type="checkbox" :disabled="disabled" :checked="currentValue" @change="change">
    </span>
    <slot></slot>
  </label>
</template>

<script>
import Emitter from '@/mixins/emitter.js';
import { findComponentUpward } from '@/utils/assist.js';
export default {
  name: 'iCheckbox',
  mixins: [Emitter],
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Number, Boolean],
      default: false
    },
    // 是否选中
    trueValue: {
      type: [String, Number, Boolean],
      default: true
    },
    // 是否选中
    falseValue: {
      type: [String, Number, Boolean],
      default: false
    },
    label: {
      type: [String, Number, Boolean]
    }
  },
  data() {
    return {
      currentValue: this.value,
      parent: null,
      group: false,
      model: [] // 这个model 存放父级的value
    }
  },
  methods: {
    change(event) {
      if (this.disabled) {
        return false;
      }
      const checked = event.target.checked;
      this.currentValue = checked;

      const value = checked ? this.trueValue : this.falseValue;
      this.$emit('input', value);

      // 在组合模式下，Checkbox 选中，就不用对 Form 派发事件了，应该在 CheckboxGroup 中派发
      if (this.group) {
        this.parent.change(this.model);
      } else {
        // checkbox 也是一个基础表单 所以想Form派发一个事件
        this.$emit('on-change', value);
        this.dispatch('iFormItem', 'on-form-chenge', value)
      }

    },
    updateModel() {
      this.currentValue = this.value === this.trueValue;
    }
  },
  watch: {
    // value 改变无法通知外部 
    value(val) {
      if (val === this.trueValue || val === this.falseValue) {
        this.updateModel();
      } else {
        throw 'Value should be trueValue or falseValue.';
      }
    }
  },
  mounted() {
    // 通过 findComponentUpward  判断是否 CheckboxGroup 有给group设置为true
    this.parent = findComponentUpward(this, 'iCheckboxGroup')
    
    if (this.parent) {
      this.group = true
    }

    if (this.group) {
      this.parent.updateModel(true)
    } else {
      this.updateModel()
    }

  }
}
</script>

<style lang="less" scoped>
</style>